package com.obrempon.credit.market.ui.fragment

import android.annotation.SuppressLint
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.viewpager.widget.ViewPager
import com.google.gson.Gson
import com.obrempon.credit.market.R
import com.obrempon.credit.market.configs.ObremponApiPath
import com.obrempon.credit.market.configs.ObremponApiUrl
import com.obrempon.credit.market.configs.ObremponApiUrl.addCommonParams
import com.obrempon.credit.market.configs.ObremponConfigs
import com.obrempon.credit.market.databinding.ObremponHomeFragmentBinding
import com.obrempon.credit.market.event.ObremponEventData
import com.obrempon.credit.market.event.ObremponEventPointType
import com.obrempon.credit.market.httptest.HttpFragment
import com.obrempon.credit.market.request.IHttpCallback
import com.obrempon.credit.market.ui.activity.ObremponApplyAct
import com.obrempon.credit.market.ui.activity.ObremponAuthStepsAct
import com.obrempon.credit.market.ui.activity.ObremponCreditRejectedAct
import com.obrempon.credit.market.ui.activity.ObremponCreditReviewingAct
import com.obrempon.credit.market.ui.activity.ObremponOrderDetailsAct
import com.obrempon.credit.market.ui.activity.ObremponPermissionsAct
import com.obrempon.credit.market.ui.dialog.ObremponLimitIncreasedDialog
import com.obrempon.credit.market.utils.ObremponDensityUtil
import com.obrempon.credit.market.utils.ObremponImageUtil
import com.obrempon.credit.market.utils.ObremponTitleBarUtil
import com.obrempon.credit.market.utils.helper.ObremponConfigsHelper
import com.obrempon.credit.market.utils.helper.ObremponCreditStatusHelper
import com.obrempon.credit.market.utils.helper.ObremponProcessHelper
import com.obrempon.credit.market.utils.helper.ObremponProductHelper
import com.obrempon.credit.market.utils.shared.ObremponSharedHelper
import com.obrempon.credit.market.utils.shared.ObremponSharedKey
import com.obrempon.credit.market.weight.viewpager.XBannerUtils
import com.obrempon.credit.market.weight.viewpager.entity.ProductBean
import com.obrempon.credit.market.weight.viewpager.transformers.Transformer
import com.obrempon.module.shapeview.layout.ShapeRelativeLayout
import org.json.JSONObject
import pub.devrel.easypermissions.EasyPermissions
import java.math.BigDecimal

/**
 * ObremponCredit
 * @Author wwdeng
 * @CreateTime: 2024/12/10 14:53
 * @Annotation：主页
 */
class ObremponHomeFragment : HttpFragment() {
    lateinit var binding: ObremponHomeFragmentBinding

    private val showProductList = arrayListOf<ProductBean>()
    //显示类型：1未申请产品列表  2已申请产品列表
    private var showType = 1
    //当前显示的产品
    private var selectedIndex = 0

    override fun getObremponRootView(inflater: LayoutInflater): View {
        binding = ObremponHomeFragmentBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initObremponView() {
        binding.homeTitleBarLayout.setPadding(0, ObremponTitleBarUtil.getStatusBarHeight(), 0, 0)
        binding.creditLimitRefreshLayout.setColorSchemeResources(R.color.theme, R.color.purple_500)
        rootViewBinding.rootLayout.setBackgroundColor(getColor(R.color.color_fff5f7fb))
        initObremponProductListView()
        initObremponEmptyView()
    }

    override fun initObremponListener() {
        binding.imgCustomer.setOnClickListener {
            showCustomerDialog("Home Page")
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_CUSTOMER,"Home Page")
        }
        binding.creditLimitRefreshLayout.setOnRefreshListener {
            onObremponRefreshData()
        }
        binding.productsLayout.setOnClickListener {
            showObremponLoading()
            showType = 1
            onObremponRefreshData()
        }
        binding.appliedLayout.setOnClickListener {
            showObremponLoading()
            showType = 2
            onObremponRefreshData()
        }
        binding.buttonApply.setOnClickListener {
            val item = showProductList[selectedIndex]
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_LOAN_APPLY,item.product)
            checkObremponPermissions()
        }
        binding.textEmpty.setOnClickListener {
            binding.productsLayout.callOnClick()
        }
    }

    override fun takeObremponData() {
        addEventPointRequestAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_HOME_START)

        showType = 1
//        checkObremponShowType()
    }

    /**
     * 刷新流程和产品列表
     */
    private fun onObremponRefreshData(){
        publishEventData(ObremponEventData(ObremponEventData.TYPE.OBREMPON_PROCESS_REFRESH))
        publishEventData(ObremponEventData(ObremponEventData.TYPE.OBREMPON_PRODUCT_REFRESH))
    }

    /**
     * 初始化产品列表
     */
    @SuppressLint("SetTextI18n")
    private fun initObremponProductListView() {
        // 设置XBanner的页面切换特效
        binding.xBanner.setPageTransformer(Transformer.Scale)
        // 设置XBanner页面切换的时间，即动画时长
        binding.xBanner.setPageChangeDuration(1000)
        binding.xBanner.setAutoPlayTime(3000)
        binding.xBanner.setSlideScrollMode(1)
        //设置是否允许用户手指滑动
        binding.xBanner.setAllowUserScrollable(true)
        //是否自动轮播
        binding.xBanner.setAutoPlayAble(false)
        //设置非自动轮播状态下是否可以循环切换
        binding.xBanner.setHandLoop(false)
        //显示指示器
        binding.xBanner.setPointsIsVisible(false)
        binding.xBanner.setShowIndicatorOnlyOne(false)
        //是否开启一屏多个模式
        binding.xBanner.setIsClipChildrenMode(true)
        //低于三张图片是否展示一屏多显模式
        binding.xBanner.setIsClipChildrenModeLessThree(true)
        //修改一屏多显模式左右间距
        binding.xBanner.setClipChildrenLeftRightMargin(XBannerUtils.dp2px(requireContext(), 60f), XBannerUtils.dp2px(requireContext(), 60f))

        //加载广告图片
        binding.xBanner.loadImage { banner, model, view, position ->
            //2、返回的图片路径为Object类型，你只需要强转成你传输的类型就行，切记不要胡乱强转！
            val item = model as ProductBean
            val unlockLayout = view.findViewById<LinearLayout>(R.id.unlockLayout)

            val itemLayout = view.findViewById<ShapeRelativeLayout>(R.id.itemLayout)
            if (item.activeFlag == "YES"){
                itemLayout.shapeDrawableBuilder.setSolidColor(getColor(R.color.color_ff0569ff)).intoBackground()
                unlockLayout.visibility = View.GONE
            } else {
                itemLayout.shapeDrawableBuilder.setSolidColor(getColor(R.color.color_ffa5acb8)).intoBackground()
                unlockLayout.visibility = View.VISIBLE
            }

            val textMaxAmount = view.findViewById<TextView>(R.id.textMaxAmount)
            textMaxAmount.text = "${item.currency} ${BigDecimal(item.amount).stripTrailingZeros().toPlainString()}"

            val textInterest = view.findViewById<TextView>(R.id.textInterest)
            textInterest.text = "${BigDecimal(item.interestRate).multiply(BigDecimal("100")).stripTrailingZeros().toPlainString()}%"

            val imgLogo = view.findViewById<ImageView>(R.id.imgLogo)
            ObremponImageUtil.instance.loadImageUrl(requireContext(),imgLogo,item.logo)

            val textTitle = view.findViewById<TextView>(R.id.textTitle)
            textTitle.text = item.name

            val statusLayout = view.findViewById<LinearLayout>(R.id.statusLayout)
            //未申请产品列表,不显示状态
            if (showType == 1){
                statusLayout.visibility = View.GONE
            } else {//已申请产品列表需要显示状态
                statusLayout.visibility = View.VISIBLE
                val imgStatusIcon = view.findViewById<ImageView>(R.id.imgStatusIcon)
                val textStatus = view.findViewById<TextView>(R.id.textStatus)
                val textRejectedReapplyDate = view.findViewById<TextView>(R.id.textRejectedReapplyDate)
                textRejectedReapplyDate.visibility = View.GONE

                val applyStatus = item.applyStatus
                val status = item.status

                if (applyStatus.endsWith("DENIED")) {//被拒绝
                    imgStatusIcon.setImageResource(R.mipmap.obrempon_product_rejected)
                    textStatus.text = getString(R.string.obrempon_home_status_rejected)
                    textStatus.setTextColor(getColor(R.color.color_ffff4f45))
                    textRejectedReapplyDate.visibility = View.VISIBLE
                    textRejectedReapplyDate.text = String.format(getString(R.string.obrempon_home_status_rejected_reapply_date),item.againApplyDate)
                } else {
                    if (status == "PENDING"){
                        if (applyStatus == "SUCCEEDED"){//放款中
                            imgStatusIcon.setImageResource(R.mipmap.obrempon_product_disbursing)
                            textStatus.text = getString(R.string.obrempon_home_status_disbursing)
                            textStatus.setTextColor(getColor(R.color.color_ffff9662))
                        } else {//审核中
                            imgStatusIcon.setImageResource(R.mipmap.obrempon_product_reviewing)
                            textStatus.text = getString(R.string.obrempon_home_status_reviewing)
                            textStatus.setTextColor(getColor(R.color.black))
                        }
                    } else {//审核中
                        imgStatusIcon.setImageResource(R.mipmap.obrempon_product_reviewing)
                        textStatus.text = getString(R.string.obrempon_home_status_reviewing)
                        textStatus.setTextColor(getColor(R.color.black))
                    }
                }
            }
        }
        binding.xBanner.setOnItemClickListener { banner, model, view, position ->
            val item = model as ProductBean
            //未申请产品列表,不显示状态
            if (showType != 1){
                val pName = item.product
                val pToken = item.token
                ObremponOrderDetailsAct.start(requireContext(),pName,pToken)
            }
        }
        binding.xBanner.setOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
            }
            override fun onPageSelected(position: Int) {
                selectedIndex = position
                val item = showProductList[position]
                binding.buttonApply.isEnabled = item.activeFlag == "YES"
                loadObremponLimitIncreasedAction()
            }
            override fun onPageScrollStateChanged(state: Int) {
            }
        })
    }

    /**
     * 初始化空提示
     */
    private fun initObremponEmptyView(){
        val showEmptyText = String.format(getString(R.string.obrempon_home_applied_empty_tips),getString(R.string.obrempon_home_applied_empty_apply_now))
        val startIndex = showEmptyText.indexOf(getString(R.string.obrempon_home_applied_empty_apply_now))
        val emptySpannable = SpannableString(showEmptyText)
        emptySpannable.setSpan(ForegroundColorSpan(getColor(R.color.color_ffff7944)), startIndex, showEmptyText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //添加下划线
        emptySpannable.setSpan(UnderlineSpan(), startIndex, showEmptyText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textEmpty.text = emptySpannable
    }

    /**
     * 切换类型
     */
    private fun checkObremponShowType(){
        selectedIndex = 0
        binding.textProducts.setTextColor(getColor(R.color.color_ffb3c3cc))
        binding.textProducts.textSize = ObremponDensityUtil.px2sp(resources.getDimension(com.obrempon.module.R.dimen.sp_14))
        binding.viewProducts.visibility = View.GONE

        binding.textApplied.setTextColor(getColor(R.color.color_ffb3c3cc))
        binding.textApplied.textSize = ObremponDensityUtil.px2sp(resources.getDimension(com.obrempon.module.R.dimen.sp_14))
        binding.viewApplied.visibility = View.GONE
        when(showType){
            1 -> {//未申请产品列表
                binding.textProducts.setTextColor(getColor(R.color.color_ff0569ff))
                binding.textProducts.textSize = ObremponDensityUtil.px2sp(resources.getDimension(com.obrempon.module.R.dimen.sp_16))
                binding.viewProducts.visibility = View.VISIBLE
                showObremponAvailableProductListView()
            }
            else -> {//已申请产品列表
                binding.textApplied.setTextColor(getColor(R.color.color_ff0569ff))
                binding.textApplied.textSize = ObremponDensityUtil.px2sp(resources.getDimension(com.obrempon.module.R.dimen.sp_16))
                binding.viewApplied.visibility = View.VISIBLE
                showObremponAppliedProductListView()
            }
        }

        if (showProductList.size > 0){
            val item = showProductList[selectedIndex]
            binding.buttonApply.isEnabled = item.activeFlag == "YES"
            loadObremponLimitIncreasedAction()
        }
    }

    /**
     * 显示未申请的产品列表
     */
    private fun showObremponAvailableProductListView(){
        showProductList.clear()
        val pList = ObremponProductHelper.takeObremponAvailableProductList()
        if (pList.size == 0){
            binding.xBanner.visibility = View.GONE
            binding.buttonApply.visibility = View.GONE
            binding.emptyLayout.visibility = View.VISIBLE
            return
        }
        binding.xBanner.visibility = View.VISIBLE
        binding.buttonApply.visibility = View.VISIBLE
        binding.emptyLayout.visibility = View.GONE
        pList.forEach {
            showProductList.add(Gson().fromJson(it.toString(), ProductBean::class.java))
        }
        binding.xBanner.setBannerData(R.layout.obrempon_home_product_item,showProductList)
        //是否开启一屏多个模式
        binding.xBanner.setIsClipChildrenMode(true)
    }

    /**
     * 显示已申请的产品列表
     */
    private fun showObremponAppliedProductListView(){
        showProductList.clear()
        val pList = ObremponProductHelper.takeObremponAppliedProductList()
        if (pList.size == 0){
            binding.xBanner.visibility = View.GONE
            binding.buttonApply.visibility = View.GONE
            binding.emptyLayout.visibility = View.VISIBLE
            return
        }
        binding.xBanner.visibility = View.VISIBLE
        binding.buttonApply.visibility = View.GONE
        binding.emptyLayout.visibility = View.GONE
        pList.forEach {
            showProductList.add(Gson().fromJson(it.toString(), ProductBean::class.java))
        }
        binding.xBanner.setBannerData(R.layout.obrempon_home_product_item,showProductList)
        //是否开启一屏多个模式
        binding.xBanner.setIsClipChildrenMode(true)
    }

    /**
     * 检查权限
     */
    private fun checkObremponPermissions(){
        //是否已阅读AppList权限说明
        val isReadAppList = ObremponSharedHelper.queryObremponSharedBoolean(ObremponSharedKey.OBREMPON_ALLIST_READ)
        val permissionList = ObremponConfigsHelper.takeObremponPermissionsList()
        //存在没有同意的权限
        if (!EasyPermissions.hasPermissions(requireContext(),*permissionList.toTypedArray()) || !isReadAppList){
            //进入权限页面
            val item = showProductList[selectedIndex]
            val pName = item.product
            val pToken = item.token
            val pAmount = item.amount
            val currency = item.currency
            ObremponPermissionsAct.start(requireContext(), pName, pToken, pAmount, currency)
            return
        }
        // 进件信息未完成
        if (ObremponProcessHelper.takeObremponAuthStepList().size > 0){
            //上报 Applist、sms
            publishEventData(ObremponEventData(ObremponEventData.TYPE.OBREMPON_SYC_AL_MS))
            val item = showProductList[selectedIndex]
            val pAmount = item.amount
            ObremponAuthStepsAct.start(requireContext(),pAmount)
            return
        }

        val creditStatus = ObremponProcessHelper.takeObremponAuthBeforeRiskStatus()
        val isCreditRejected = ObremponCreditStatusHelper.ObremponCreditStatusRepository().isCreditRejected(creditStatus)
        //授信被拒绝 - 拒绝页面
        if (isCreditRejected){
            onIntent(ObremponCreditRejectedAct::class.java)
            return
        }

        val isCreditReviewing = ObremponCreditStatusHelper.ObremponCreditStatusRepository().isCreditReviewing()
        //进件信息已完成 && 授信中 - 授信状态查询页面
        if (isCreditReviewing){
            onIntent(ObremponCreditReviewingAct::class.java)
            return
        }

        //权限已全部同意 && 进件信息已完成 && 授信已完成 - 申贷试算页面
        val item = showProductList[selectedIndex]
        val pName = item.product
        val pToken = item.token
        when(pName){
            ObremponConfigs.OBREMPON_APPNAME -> {//主产品
                enterObremponApplyAction(pName,pToken)
            }
            else -> {
                onObremponCopyProductToChildProductAction(pName)
            }
        }
    }

    /**
     * 进入申贷页面
     */
    private fun enterObremponApplyAction(pName: String,pToken: String){
        //上报 Applist、sms
        publishEventData(ObremponEventData(ObremponEventData.TYPE.OBREMPON_SYC_AL_MS))
        ObremponApplyAct.start(requireContext(),pName,pToken)
    }

    /**
     * 额度增加提示
     */
    private fun showObremponProductLimitIncreasedDialog(data: JSONObject){
        val item = showProductList[selectedIndex]
        data.put("pLogo",item.logo)
        data.put("pName",item.name)
        data.put("pToken",item.token)
        data.put("product",item.product)
        val dialog = ObremponLimitIncreasedDialog(requireContext(),data.optString("product"),object : ObremponLimitIncreasedDialog.IDialogCallback{
            override fun onClick(view: View?) {
                //申请
                binding.buttonApply.callOnClick()
            }
        })
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(false)
        dialog.show()
        dialog.showObremponLimitIncreasedData(data)
    }

    override fun onObremponPublishEvent(event: ObremponEventData) {
        super.onObremponPublishEvent(event)
        when (event.eventType) {
            ObremponEventData.TYPE.OBREMPON_PROCESS_REFRESHED -> { //刷新流程完成
            }

            ObremponEventData.TYPE.OBREMPON_ORDER_REFRESHED -> {//订单刷新完成
            }

            ObremponEventData.TYPE.OBREMPON_PRODUCT_REFRESHED -> {//刷新产品列表完成
                checkObremponShowType()
            }

            ObremponEventData.TYPE.OBREMPON_PRODUCT_FINISHED -> {//刷新产品列表完成
                hideObremponLoading()
            }

            ObremponEventData.TYPE.OBREMPON_SHOW_AUTHENTICATION -> {
            }
            else -> {

            }
        }
    }

    /**
     * 复制主产品信息到目标产品
     */
    private fun onObremponCopyProductToChildProductAction(targetProduct: String,isApply: Boolean = true){
        val item = showProductList[selectedIndex]
        showObremponLoading()
        val params = JSONObject()
            .addCommonParams()
            .apply {
                put("path",ObremponApiPath.OBREMPON_PATH.OBREMPON_API_LOAN_PRODUCT_COPY_PATH)
                put("sourceProduct", ObremponConfigs.OBREMPON_APPNAME)
                put("targetProduct",targetProduct)
            }
        val httpUrl = ObremponApiUrl.queryEasyHttpUrl()
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                var pToken = ""
                if (obj != null){
                    pToken = obj.optString("token","")
                }
                if (pToken.isEmpty()){
                    pToken = item.token
                }
                val pName = item.product
                when(isApply){
                    true -> {//去申请
                        enterObremponApplyAction(pName,pToken)
                    }
                    else -> {//进入权限
                        val pAmount = item.amount
                        val currency = item.currency
                        ObremponPermissionsAct.start(requireContext(), pName, pToken, pAmount, currency)
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideObremponLoading()
            }
        })
    }

    /**
     * 加载产品额度是否增加
     */
    private fun loadObremponLimitIncreasedAction(){
        if (showType != 1){
            //未申请产品列表
            return
        }
        val item = showProductList[selectedIndex]
        if (item.activeFlag != "YES"){
            //不可申请
            return
        }
        if (item.token.isNullOrEmpty()){
            //还没有复制子产品信息
            return
        }
        val params = JSONObject()
            .addCommonParams()
            .apply {
                put("path",ObremponApiPath.OBREMPON_PATH.OBREMPON_API_LIMIT_UP_PATH)
                put("product", item.product)
                put("token",item.token)
            }
        //todo 测试提额dialog
//        params.put("selectAmount","2000")
        val httpUrl = ObremponApiUrl.queryEasyHttpUrl()
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null && obj.optString("openFlag") == "YES"){
                    showObremponProductLimitIncreasedDialog(obj)
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    override fun hideObremponLoading() {
        super.hideObremponLoading()
        binding.creditLimitRefreshLayout.isRefreshing = false
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_HOME_END)
    }
}